<template>
  <div ref="element">
    <van-popup
      v-model="vanpopup"
      position="bottom"
      @open="onOpen"
      :style="{ height: '80%' }"
      closeable
      :close-icon-position="isMulti ? 'top-left' : 'top-right'"
      :close-on-click-overlay="false"
    >
      <div class="popup-title">
        {{ title }}
        <div
          v-if="this.isMulti"
          class="confirm-btn"
          @click="submit()"
        >
          {{ confirmButton }}
        </div>
      </div>

      <div class="popup-content">
        <div class="risk-check">
    
          <template v-if="!this.isMulti">
            <van-radio-group
              @change="handleRadioChange"
              v-model="radioResult"
            >
              <van-tabs
                v-model="active"
                @change="change"
                v-if="tab"
                title-active-color="#00c1de"
              >
                <van-tab
                  v-for="(item, index) in pageData"
                  :title="item.title"
                  :key="index"
                  :name="index"
                >
                  <van-list
                    :finished="finished"
                    v-model="loading"
                    offset="100"
                    @load="loadMore"
                    finished-text="没有更多了"
                  >
                    <slot />
                  </van-list>
                </van-tab>
              </van-tabs>
              <van-list
                :finished="finished"
                v-model="loading"
                v-if="!tab"
                offset="100"
                @load="loadMore"
                finished-text="没有更多了"
              >
                <slot />
              </van-list>
            </van-radio-group>
          </template>
          <template v-else>
            <div
              ref="selected"
              v-if="tab"
            >
              <template v-for="(item, index) in resultData">
                <div
                  style="margin: 2px 0px 2px 5px"
                  :key="index"
                >
                  <van-tag
                    closeable
                    size="medium"
                    type="primary"
                    color="#00c1de"
                    text-color="#FFFFFF"
                    @close="close(index, item)"
                  >
                    {{ item[option.name] }}
                  </van-tag>
                </div>
              </template>
            </div>

            <van-checkbox-group
              ref="checkboxGroup"
              v-model="selecteData"
              @change="handleChange"
            >
              <van-tabs
                v-model="active"
                @change="change"
                v-if="tab"
                title-active-color="#00c1de"
              >
                <van-tab
                  v-for="(item, index) in pageData"
                  :title="item.title"
                  :key="index"
                  :name="index"
                >
                  <van-list
                    :finished="finished"
                    v-model="loading"
                    offset="100"
                    @load="loadMore"
                    finished-text="没有更多了"
                  >
                    <slot />
                  </van-list>
                </van-tab>
              </van-tabs>
              <van-list
                :finished="finished"
                v-model="loading"
                v-if="!tab"
                offset="100"
                @load="loadMore"
                finished-text="没有更多了"
              >
                <slot />
              </van-list>
            </van-checkbox-group>
            <div
              class="choose_btm"
              v-if="this.isMulti && !tab"
            >
              <div class="choose_cancel">
                <van-button
                  class="mr-10"
                  type="warning"
                  size="mini"
                  @click="checkAll"
                >全选</van-button>
                <van-button
                  class="mr-10"
                  type="warning"
                  @click="toggleAll"
                  size="mini"
                >取消全选</van-button>
                <div
                  class="choose-people"
                  @click="openSelectUser"
                >
                  已选择{{ selecteData.length }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </van-popup>
    <div>
      <van-dialog
        v-model="showSelectData"
        title="已选"
        show-cancel-button
        @confirm="confirmSelect"
        @cancel="cancelSelect"
      >
        <div :style="'height: ' + height + 'px; overflow: auto'">
          <slot name="seletedSlot" />
        </div>
      </van-dialog>
    </div>
  </div>
</template>
<script>
/**
 * DialogPageList 带搜索tab过滤的分页列表弹出框
 * @property {String} title 标题
 * @property {String} confirmButton 完成或者确认按钮名称
 * @property {String} placeholder 搜索栏Placeholder
 * @property {Number} maxlength 输入最大长度
 * @property {String} url 请求数据的path
 * @property {Object} params 搜索框条件对象
 *  params: {
      type: Array,
      default: () => [
        {
          title: "公司检查表",
          Name: "Keywords",
          dataType: "CompanyCMPLList",
          page: -1,
          limit: 10,
        },
        {
          title: "公共检查表",
          Name: "Keywords",
          dataType: "SysCMPLList",
          page: -1,
          limit: 10,
        },
        {
          title: "我的检查表",
          Name: "Keywords",
          dataType: "UserList",
          page: -1,
          limit: 10,
        },
      ],
    },
 * @event {Function} initList 数据回调    @initList="_initList" 返回数据为list
 * _initList(list){
      this.list = list
    },
 */
import { deepClone } from "@/utils";

export default {
  props: {
    isMulti: {
      type: Boolean,
      default: () => false,
    },
    isPage: {
      type: Boolean,
      default: () => true,
    },
    title: {
      type: String,
      default: "选择",
    },
    confirmButton: {
      type: String,
      default: "完成",
    },
    placeholder: {
      type: String,
      default: "搜索",
    },
    maxlength: {
      type: [Number, String],
      default: 100,
    },
    show: {
      type: Boolean,
      default: false,
    },
    value2: {
      type: [Number, String],
      default: "",
    },
    url: {
      type: String,
      default: "",
    },
    tab: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Array,
      default: () => [],
    },
    option: {
      type: Object,
      default: function () {
        return { name: "ChnName", code: "UserName" };
      },
    },
    isOpenNew: {
      type: Boolean,
      default: false,
    },
    rowIndex: {
      type: [Number, String],
      default: () => 0,
    },
    isFuzzyQuery: {
      type: Boolean,
      default: false,
    },
    fuzzyKey: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loaded: false,
      searchVal: "",
      active: 0,
      conditions: [],
      pageData: [],
      list: [],
      result: [],
      resultData: [],
      userlist: [],
      userSellist: [],
      loading: false,
      finished: false,
      count: 0,
      completeHeight: 0,
      height: 0,
      showSelectData: false,
      ids: [],
      localParams: [],
      first: false,
      selecteData: [],
      isInit: true,
      radioResult: "",
      previousRowIndex: -1,
      urlArr: [],
    };
  },
  watch: {
    value2: {
      immediate: true,
      handler(newSearchVal) {
        this.searchVal = newSearchVal;
      },
    },
    searchVal(newVal, oldVal) {
      this.$emit("input", newVal);
    },
    // params: {
    //   handler(preParams) {
    //     preParams.forEach((item, index, arr) => {
    //       Object.assign(this.localParams[index], item);
    //     });
    //   },
    //   deep: true,
    // },
  },
  computed: {
    vanpopup: {
      get() {
        return this.show;
      },
      set(value) {
        this.$emit("update:show", value);
      },
    },
  },
  mounted() {
    this.height =
      document.documentElement.clientHeight * 0.5 > 270
        ? 270
        : document.body.documentElement;
  },
  methods: {
    init() {
      this.first = true;
      this.urlArr = [];
      this.pageData = deepClone(this.params);
      this.localParams = this.params;
      if (this.tab && !this.url) {
        if (this.localParams) {
          for (var i = 0; i < this.localParams.length; i++) {
            if (this.localParams[i].hasOwnProperty("url")) {
              this.urlArr.push(this.localParams[i].url);
              delete this.localParams[i].url;
            }
          }
        }
      }
    },
    onOpen() {
      this.$emit("onOpen");
      if (this.pageData.length == 0){
        this.init();
      }else{
        if(this.isOpenNew && this.isMulti){
          this.resultData=[];
          this.result=[];
          this.toggleAll();
        }
      }
      this.searchVal = "";
      if (
        this.isOpenNew ||
        this.previousRowIndex === -1 ||
        this.previousRowIndex != this.rowIndex
      ) {
        this.confirm();
      } else {
        if (!this.loaded) {
          //this.loaded = true;
          this.confirm();
        }
      }
    },
    change() {
      this.$emit("initActive", this.active);
      this.loading = false;
      this.finished = false;
      this.confirm();
    },
    confirm() {
      this.localParams[this.active].page = 0;
      let hasKeywords = "keywords" in this.localParams[this.active];
      if (hasKeywords) {
        this.localParams[this.active].keywords = this.searchVal;
      }
      var conditions = [];
      if (this.searchVal && !hasKeywords) {
        conditions.push({
          Name: "Keywords",
          DisplayName: this.searchVal,
          Value: this.searchVal,
          Operator: "like",
          DataType: "String",
        });
      }
      this.conditions = conditions;
      this.localParams[this.active].conditions = JSON.stringify(conditions);
      this.getList();
    },
    clear() {
      this.searchVal = "";
      this.loading = false;
      this.finished = false;
      this.confirm();
    },
    loadMore() {
      if (!this.first) {
        this.loading = true;
        this.localParams[this.active].page++;
        let currentUrl = this.getCurrentUrl();
        this.$axios
          .get(currentUrl, { params: this.localParams[this.active] })
          .then((res) => {
            this.loading = false;
            this.localParams[this.active].page = res.data.PageIndex;
            this.list = this.list.concat(res.data.Data);
            this.pageData[this.active].data = this.list;
            this.$emit("initList", this.list);
            if (!res.data.HasNextPage) {
              this.finished = true;
            } else {
              this.finished = false;
            }
          })
          .catch((err) => {
            console.log("err", err);
            this.finished = true;
          });
      }
    },
    close(idx, item) {
      this.resultData.splice(idx, 1);
      this.result.splice(idx, 1);
      this.selecteData.splice(
        this.selecteData.findIndex((item2) => item2 === item[this.option.code]),
        1
      );
    },
    getList() {
      if (this.isPage) {
        this.getPageList();
      } else {
        this.getNoPageList();
      }
    },
    getPageList() {
      this.loading = true;
      let currentUrl = this.getCurrentUrl();
      let _this = this;
      _this.$axios
        .get(currentUrl, { params: this.localParams[this.active] })
        .then((res) => {
          _this.loading = false;
          if (!res.data.HasNextPage) {
            _this.finished = true;
          }
          _this.localParams[_this.active].page = res.data.PageIndex;
          _this.list = res.data;
          _this.pageData[_this.active].data = _this.list;
          _this.$emit("initList", _this.list);
          _this.first = false;
        })
        .catch((err) => {
          console.log("err", err);
          _this.finished = true;
        });
    },
    getNoPageList() {
      this.loading = true;
      let currentUrl = this.getCurrentUrl();
      let _this = this;
      _this.$axios
        .get(currentUrl, { params: this.localParams[this.active] })
        .then((res) => {
          _this.loading = false;
          _this.finished = true;
          _this.list = res.data;
          if (_this.isFuzzyQuery && _this.fuzzyKey && _this.searchVal) {
            _this.list = _this.fuzzyQuery(
              _this.list,
              _this.searchVal,
              _this.fuzzyKey
            );
          }
          _this.pageData[_this.active].data = _this.list;
          _this.$emit("initList", _this.list);
          _this.first = false;
        })
        .catch((err) => {
          console.log("err", err);
          _this.finished = true;
        });
    },
    fuzzyQuery(list, keyWord, type) {
      var arr = [];
      list.map((item) => {
        if (item[type].indexOf(keyWord) >= 0) {
          arr.push(item);
        }
      });
      return arr;
    },
    handleChange(ids) {
      if (this.tab) {
        let _this = this;
        ids.forEach((id) => {
          if (!_this.checkExsit(_this.resultData, _this.option.code, id)) {
            _this.pageData[_this.active].data.forEach((item) => {
              if (item[_this.option.code] == id) {
                var item2 = Object.assign({ code: "", name: "" }, item);
                item2.code = item2[_this.option.code];
                item2.name = item2[_this.option.name];
                _this.resultData.push(item2);
              }
            });
          }
        });
        let newResultData = [];
        for (var m = 0; m < this.resultData.length; m++) {
          if (this.checkArrExsit(ids, this.resultData[m][this.option.code])) {
            newResultData.push(this.resultData[m]);
          }
        }
        this.resultData = newResultData;
        console.log("handleChange  111")  
        this.$emit("setData", this.resultData);
      } else {
        console.log("handleChange")
        console.log(ids)
        console.log(this.list)
        ids.forEach((id) => {
          this.list.map((innerItem) => {
            if (id == innerItem[this.option.code]) {
              let flag = false; // 判断是已选中需要取消(true)还是未选中需要选中(false)
              this.userlist.forEach((user) => {
                if (id == user.code) {
                  flag = true;
                }
              });
              if (!flag) {
                var item2 = Object.assign({ code: "", name: "" }, innerItem);
                item2.code = item2[this.option.code];
                item2.name = item2[this.option.name];
                this.userlist.push(item2);
              }
            }
          });
        });
        for (var i = 0; i < this.userlist.length; i++) {
          var item = this.userlist[i];
          this.list.map((innerItem) => {
            if (innerItem[this.option.code] == item.code) {
              let flag = false;
              ids.forEach((idItem) => {
                if (item.code == idItem) {
                  flag = true;
                }
              });
              if (!flag) {
                this.userlist.splice(i, 1);
                i--;
              }
            }
          });
        }
        console.log("handleRadioChange  44")
        this.$emit("setData", this.userlist);
      }
    },
    checkAll() {
      this.$refs.checkboxGroup.toggleAll(true);
    },
    toggleAll() {
      this.$refs.checkboxGroup.toggleAll(false);
    },
    submit() {
      let selectCodes = [];
      let selectNames = [];
      this.resultData.map((item, index) => {
        selectCodes.push(item[this.option.code]);
        selectNames.push(item[this.option.name]);
      });
      let params = {
        code: selectCodes.join(","),
        name: selectNames.join(","),
      };
      let callbackValue = this.tab ? params : this.userlist;
      this.$emit("callbackDialog", callbackValue,this.resultData);
    },
    openSelectUser() {
      this.showSelectData = true;
    },
    deleteSelect(code) {
      this.userlist = this.userlist.filter((item) => {
        return item[this.option.code] != code;
      });
      this.ids.push(code);
      this.selecteData.splice(this.selecteData.indexOf(code), 1);
    },
    confirmSelect() {},
    cancelSelect() {
      this.showSelectData = false;
    },
    initSeletedData(data) {
      if (!this.isMulti) {
        if (data.length > 0) {
          this.radioResult = data[0].code;
        }
      } else {
        this.selecteData = [];
        this.userlist = [];
        if (data && data.length > 0) {
          for (var i = 0; i < data.length; i++) {
            this.selecteData.push(data[i][this.option.code]);
          }
        }
        this.userlist = data;
        if (this.tab) {
          if (data && data.length > 0) {
            for (var j = 0; j < data.length; j++) {
              var item = data[j];
              if (
                !this.checkExsit(
                  this.resultData,
                  this.option.code,
                  item[this.option.code]
                )
              ) {
                var item2 = Object.assign({ code: "", name: "" }, item);
                item2.code = item[this.option.code];
                item2.name = item[this.option.name];
                this.resultData.push(item2);
              }
            }
          }
        }
      }
    },
    checkExsit(arr, field, value) {
      if (arr.length == 0) {
        return false;
      }
      var flag = false;
      for (var i = 0; i < arr.length; i++) {
        if (arr[i][field] == value) {
          flag = true;
          break;
        }
      }
      return flag;
    },
    checkArrExsit(arr, value) {
      if (arr.length == 0) {
        return false;
      }
      var flag = false;
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] == value) {
          flag = true;
          break;
        }
      }
      return flag;
    },
    handleRadioChange(id) {
      const newData = this.list.filter((item) => item[this.option.code] === id);
      if (newData.length > 0) {
        let resultRadio = Object.assign({ code: "", name: "" }, newData[0]);
        resultRadio.code = newData[0][this.option.code];
        resultRadio.name = newData[0][this.option.name];
        console.log("handleChange  777")
        this.$emit("setData", resultRadio);
        //this.$emit("callbackDialog", resultRadio);
        //this.vanpopup = false;
      } else {
        var item = {
          code: id,
          name: "",
        };
        console.log("handleChange  555")
        this.$emit("setData", item);
      }
    },
    getCurrentUrl() {
      let currentUrl = this.url;
      if (this.tab && !this.url) {
        currentUrl = this.urlArr[this.active];
      }
      return currentUrl;
    },
  },
};
</script>
<style lang="less" scoped>
.confirm-btn {
  position: absolute;
  right: 10px;
  top: 0px;
  font-size: 12px;
}
.popup-title {
  text-align: center;
}
</style>
<style lang="less" scoped>
.choose_btm {
  display: flex;
  width: 100%;
  justify-content: space-between;
  position: fixed;
  bottom: 0px;
  padding-top: 5px;
  padding-bottom: 5px;
  border-top: 1px solid #efefef;
  background-color: #fff;
  .choose_cancel {
    padding: 0 10px;
    display: flex;
    align-items: center;
    float: left;
  }
  .choose_confirm {
    float: right;
    border-radius: 0;
  }
}
.risk_item_buton {
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>